package com.resoft.bigdata.p2p.record;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.hbase.util.Bytes;

public class MonthlyTodoRecord  implements RecordInterface {
	public static final String TABLE_NAME = "MONSTAT_TODO";
	public static final String[] FAMILY_NAMES= {"F1"};
	
	public static final byte[] DATE_STRINGS  = Bytes.toBytes("DATE_STRINGS");
	public static final byte[] ISDONE  = Bytes.toBytes("ISDONE");

	
	private long ts;
	private List<String> dateStrings = new ArrayList<String>();
	private boolean isDone=false;
	private byte[] storedKey;
	
	public long getTs(){
		return ts;
	}
	
	public void setTs(long ts){
		this.ts = ts;
	}
	
	public void addDate(String dateString){
		if(dateString != null && !dateString.isEmpty()){
			dateStrings.add(dateString);
		}
	}


	public boolean isDone() {
		return isDone;
	}

	public void setDone(boolean isDone) {
		this.isDone = isDone;
	}
	
	

	public byte[] getStoredKey() {
		return storedKey;
	}

	public void setStoredKey(byte[] storedKey) {
		this.storedKey = storedKey;
	}

	@Override
	public String getTableName() {
		return TABLE_NAME;
	}

	@Override
	public String[] getFamilies() {
		return FAMILY_NAMES;
	}

	@Override
	public byte[] getRowKey() throws Exception {
		return Bytes.toBytes(ts);
	}
		

	@Override
	public Map<byte[], byte[]> getCells() {
		Map<byte[], byte[]> cells = new HashMap<byte[], byte[]>();
		StringBuilder sb = new StringBuilder();
		if(!dateStrings.isEmpty()){
			for(String s: dateStrings){
				sb.append(s + ",");
			}
			sb.delete(sb.length()-1, sb.length()-1);
			String sdates = sb.toString();
			byte[] value = Bytes.toBytes(sdates);
			cells.put(DATE_STRINGS, value);
		}
		
		String isDoneString = "NO";
		if(isDone){
			isDoneString = "YES";
		}
		cells.put(ISDONE, Bytes.toBytes(isDoneString));
	
		return cells;
	}

	@Override
	public String getCreatePhoenixTableSQL() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setValue(byte[] key, byte[] value) {
		String keyString = Bytes.toString(key).toUpperCase();
		
		if(Bytes.toString(DATE_STRINGS).equalsIgnoreCase(keyString)){
			String dateStrings = Bytes.toString(value);
			String[] dates = dateStrings.split(",");
			if(dates != null && dates.length > 0){
				this.dateStrings.clear();
				for(int i=0; i<dates.length; i++){
					this.dateStrings.add(dates[i]);
				}
			}
		}else if(Bytes.toString(ISDONE).equalsIgnoreCase(keyString)){
			boolean isDone = false;
			if(Bytes.toString(value).equalsIgnoreCase("YES")){
				isDone = true;
			}
			
			this.setDone(isDone);
		}
		
	}

	@Override
	public void setStoredRowKey(byte[] lastRow) {
		this.storedKey = lastRow;		
	}

	public List<String> getDateStrings() {
		return dateStrings;
	}
	
	
	
}
